﻿using System;
using System.Diagnostics;
using MouseExtender.Logic.Common;
using System.Threading;

namespace MouseExtender.Logic.Helpers
{
    /// <summary>
    /// Set of static methods dealing with memory consumption.
    /// </summary>
    public class MemoryHelper
    {
        private static void SetWorkingSet(int lnMinSize, int lnMaxSize)
        {
            try
            {
                Process loProcess = Process.GetCurrentProcess();
                loProcess.MaxWorkingSet = (IntPtr)lnMaxSize;
                loProcess.MinWorkingSet = (IntPtr)lnMinSize;
            }
            catch (Exception ex)
            {
                Logger.HandleNonCriticalError(ex);
            }
        }

        public static void MinimizeWorkingSet(bool asynch)
        {
            int size = 10 * 1024 * 1024; //10mb
            if (asynch)
            {
                ThreadPool.QueueUserWorkItem((o) => SetWorkingSet(size, size));
            }
            else
            {
                SetWorkingSet(size, size);
            }
        }

        public static void GarbageCollectAndMinimizeMemoryUsage()
        {
            GC.Collect();
            MinimizeWorkingSet(false);
        }
    }
}
